package com.rytong.tools.ui;

import java.util.Calendar;
import java.util.HashMap;
import java.util.TimeZone;
import com.rytong.tools.ui.NumericWheelAdapter;
import com.rytong.tools.ui.LPTextField.MyLPTextField;
import com.rytong.tools.utils.LPToastUtil;
import com.rytong.tools.utils.Utils;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

public class LPDateFieldView extends LinearLayout {
    Activity at_;
    WheelView yearWheel_, monthWheel_, dayWheel_;
    private Button confirm_,cancel_;
    private int year_, month_, day_;
    private int daysOfMonth_;

    private LPTextField dateField_;
    private int year_width_ = 140;
    private int month_width_ = 80;
    private int day_width_ = 80;
    public Dialog dialog_ = null;
    public LPDateFieldView(Context context, LPTextField dateField) {
        super(context);
        // TODO Auto-generated constructor stub
        at_ = (Activity) context;
        dateField_ = dateField;
        this.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        this.setGravity(Gravity.CENTER);

        init(at_);

        yearWheel_.addScrollingListener(new OnWheelScrollListener() {

            @Override
            public void onScrollingFinished(WheelView wheel) {
                // TODO Auto-generated method stub
                year_ = wheel.getCurrentItem() + 1;
                resetDate(getDaysOfMonth(year_, month_));
            }

            @Override
            public void onScrollingStarted(WheelView wheel) {
                // TODO Auto-generated method stub
            }
        });

        monthWheel_.addScrollingListener(new OnWheelScrollListener() {

            @Override
            public void onScrollingFinished(WheelView wheel) {
                // TODO Auto-generated method stub
                month_ = wheel.getCurrentItem() + 1;
                resetDate(getDaysOfMonth(year_, month_));
            }

            @Override
            public void onScrollingStarted(WheelView wheel) {
                // TODO Auto-generated method stub
            }
        });

        dayWheel_.addScrollingListener(new OnWheelScrollListener() {

            @Override
            public void onScrollingFinished(WheelView wheel) {
                // TODO Auto-generated method stub
                day_ = wheel.getCurrentItem() + 1;
            }

            @Override
            public void onScrollingStarted(WheelView wheel) {
                // TODO Auto-generated method stub
            }
        });
        
        //确定按钮
        confirm_.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
                setDate();
                if(null != dialog_ && dialog_.isShowing()){
                	dialog_.dismiss();
                }
			}
		});
        
        //取消按钮
        cancel_.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
                if(null != dialog_ && dialog_.isShowing()){
                	dialog_.dismiss();
                }
			}
		});
    }

    private void init(Activity at) {
        // TODO Auto-generated method stub
        /*
         * 实例化日期，并得到当前日期
         */
        Calendar cal;
        cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        year_ = cal.get(Calendar.YEAR);
        month_ = cal.get(Calendar.MONTH) + 1;
        day_ = cal.get(Calendar.DAY_OF_MONTH);
        try {
            String value = (String) dateField_.getPropertyByName("value");
            value = value.trim();
            if (value.length() > 0) {
                if (value.contains("-")) {
                    year_ = Integer.parseInt(value.substring(0, value.indexOf("-")));
                    value = value.substring(value.indexOf("-") + 1);
                    if (value.contains("-")) {
                        month_ = Integer.parseInt(value.substring(0, value.indexOf("-")));
                        day_ = Integer.parseInt(value.substring(value.indexOf("-") + 1));
                    }
                } else {
                    if (value.length() == 8) {
                        year_ = Integer.parseInt(value.substring(0, 4));
                        month_ = Integer.parseInt(value.substring(4, 6));
                        day_ = Integer.parseInt(value.substring(6));
                    }
                }
            }
        } catch (Exception e) {
            Utils.printException(e);
            year_ = cal.get(Calendar.YEAR);
            month_ = cal.get(Calendar.MONTH) + 1;
            day_ = cal.get(Calendar.DAY_OF_MONTH);
        }
        daysOfMonth_ = getDaysOfMonth(year_, month_);

        yearWheel_ = new WheelView(at);
        yearWheel_.setLayoutParams(new LinearLayout.LayoutParams(Utils.getScaledValueX(year_width_),
                LayoutParams.WRAP_CONTENT));
        yearWheel_.setAdapter(new NumericWheelAdapter(1, 9999, "年"));
        yearWheel_.setCurrentItem(year_ - 1);
        yearWheel_.setCyclic(true);

        monthWheel_ = new WheelView(at);
        monthWheel_.setLayoutParams(new LinearLayout.LayoutParams(Utils.getScaledValueX(month_width_),
                LayoutParams.WRAP_CONTENT));
        monthWheel_.setAdapter(new NumericWheelAdapter(1, 12, "月"));
        monthWheel_.setCurrentItem(month_ - 1);
        monthWheel_.setCyclic(true);

        dayWheel_ = new WheelView(at);
        dayWheel_.setLayoutParams(new LinearLayout.LayoutParams(Utils.getScaledValueX(day_width_),
                LayoutParams.WRAP_CONTENT));
        dayWheel_.setAdapter(new NumericWheelAdapter(1, daysOfMonth_, "日"));
        dayWheel_.setCurrentItem(day_ - 1);
        dayWheel_.setCyclic(true);

        LinearLayout layout = (LinearLayout) LayoutInflater.from(at).inflate(Utils.getResourcesId(at, "layout_select_popup", "layout"), null);
        LinearLayout wheelParent = (LinearLayout)layout.findViewById(Utils.getResourcesId(at, "wheelParent", "id"));
        confirm_ = (Button)layout.findViewById(Utils.getResourcesId(at, "confirm", "id"));
        cancel_ = (Button)layout.findViewById(Utils.getResourcesId(at, "cancel", "id")); 
     
        wheelParent.addView(yearWheel_);
        wheelParent.addView(monthWheel_);
        wheelParent.addView(dayWheel_);
        
        this.addView(layout);
    }

    // 得到用户选择的日期，并且格式化
    public void setDate() {
        String dateStr = "";
        String showvalue = (String) dateField_.getPropertyByName("showFormat");
        if (null != showvalue && !showvalue.equals("")) {
            if (showvalue.contains("-")) {
                dateStr = year_ + "-" + (month_ < 10 ? ("0" + month_) : month_) + "-"
                        + (day_ < 10 ? ("0" + day_) : day_);
            } else {
                dateStr = year_ + "" + (month_ < 10 ? ("0" + month_) : month_) + "" + (day_ < 10 ? ("0" + day_) : day_);
            }
        } else {
            // 不给showFormat属性默认带"-"
            dateStr = year_ + "-" + (month_ < 10 ? ("0" + month_) : month_) + "-" + (day_ < 10 ? ("0" + day_) : day_);
        }
        // 拼接上星期几。
        if(showvalue != null && showvalue.contains("EEEE")){ // 带EEEE字段格式，显示星期几。
        	Calendar cal = Calendar.getInstance();
        	cal.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 设置时区。
        	cal.set(Calendar.YEAR, year_); // 设置年份。
            cal.set(Calendar.MONTH, month_ - 1); // 设置月份。
            cal.set(Calendar.DAY_OF_MONTH, day_); // 设置日期。
        	dateStr += " " + Utils.getDayOfWeek(at_, cal); // 取得星期几。
        }
        ((MyLPTextField) dateField_.realView_).setText(dateStr);
        ((MyLPTextField) dateField_.realView_).invalidate();
        if(dateField_.property_ == null){
        	dateField_.property_ = new HashMap<String, String>();
        }
        dateField_.property_.put("text", dateStr);

        String value = (String) dateField_.getPropertyByName("valueFormat");
        if (null != value && !value.equals("")) {
            if (value.contains("-")) {
                dateStr = year_ + "-" + (month_ < 10 ? ("0" + month_) : month_) + "-"
                        + (day_ < 10 ? ("0" + day_) : day_);
            } else {
                dateStr = year_ + "" + (month_ < 10 ? ("0" + month_) : month_) + "" + (day_ < 10 ? ("0" + day_) : day_);
            }
        } else {
         // 不给valueFormat属性默认不带"-"
            dateStr = year_ + "" + (month_ < 10 ? ("0" + month_) : month_) + "" + (day_ < 10 ? ("0" + day_) : day_);
        }
        if(dateField_.property_ == null){
        	dateField_.property_ = new HashMap<String, String>();
        }
        
        if(LPToastUtil.getInstance().isBranchBank){
          	 String dates = year_ + "" + (month_ < 10 ? ("0" + month_) : month_) + "" + (day_ < 10 ? ("0" + day_) : day_);
          	 dateField_.property_.put("text", dates);
          	((MyLPTextField) dateField_.realView_).setText(dates);
          }

        dateField_.property_.put("value", dateStr);
    }

    protected void resetDate(int day) {
        // TODO Auto-generated method stub

        if (day != dayWheel_.getAdapter().getItemsCount()) {
            dayWheel_.setCurrentItem(0, true);
            dayWheel_.setAdapter(new NumericWheelAdapter(1, day, "日"));
        }
        //setDate();
    }

    // 根据年份获得每个月的天数,保证每个月的天数是准确的
    private int getDaysOfMonth(int year, int month) {
        switch (month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            return 31;
        case 4:
        case 6:
        case 9:
        case 11:
            return 30;
        case 2:
            if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
                return 29;
            } else {
                return 28;
            }
        default:
            return 0;
        }
    }
}